package com.kevin.crossfadedemo;

import android.os.Bundle;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ScrollView;

@SuppressLint("InlinedApi")
public class MainActivity extends Activity {

	View 	m_oScrollView;
	View 	m_oLoadingSpinner;
	int 	m_nTimes;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		m_oScrollView = (View) findViewById(R.id.content);
		m_oLoadingSpinner = (View) findViewById(R.id.loading_spinner);
		m_nTimes = 0;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuItem item = menu.add(0, 0, 0, "start");
		item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (0 == item.getItemId()) {
			StartAnim();
			return true;
		}
		
		return false;
	}

	private void StartAnim() {
		if (m_nTimes % 2 == 0) {
			m_oScrollView.setAlpha(0f);
			m_oScrollView.setVisibility(View.VISIBLE);

			m_oScrollView.animate().alpha(1f).setDuration(500).setListener(null);
			m_oLoadingSpinner.animate().alpha(0f).setDuration(500)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							m_oLoadingSpinner.setVisibility(View.GONE);
						}
					});
		} else {
			m_oLoadingSpinner.setAlpha(0f);
			m_oLoadingSpinner.setVisibility(View.VISIBLE);
			
			m_oLoadingSpinner.animate().alpha(1f).setDuration(500).setListener(null);
			m_oScrollView.animate().alpha(0f).setDuration(500)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							m_oScrollView.setVisibility(View.GONE);
						}
					});
		}
		
		m_nTimes++;
	}

}
